var express = require('express');
var router = express.Router();
var StaticizeUtil = require('../../../common/util/StaticizeUtil');
var path=require('path');
var CONFIG = require('../../../common/config');
var CommonUtil = require('../../../common/util/CommonUtil');
var CODE = require('../../../common/code');
var checkUtil = require('./../util/checkUtil');
var async  = require( 'async'); // 同步控制
var tg3Util  = require('./tg3Util');
var superagent = require('superagent');

var ItbBaseModel = require('./../../../common/mysql/mapping/ItbBaseModel');
var ItbActivityModel = require('./../../../common/mysql/mapping/ItbActivityModel');
var ItbActivityRModel = require('./../../../common/mysql/mapping/ItbActivityRModel');
var ItbTemplateModel = require('./../../../common/mysql/mapping/ItbTemplateModel');
var TgDesignDocModel = require('./../../../common/mysql/mapping/TgDesignDocModel');
var TgKeywordModel = require('./../../../common/mysql/mapping/TgKeywordModel');

//------------------------------------------------------------------
var luaSearchRedisMgrUtil  = require('./luaSearchRedisMgrUtil');



//------------------------------------------------------------------
var luaSearchUtil = (function () {
    function luaSearchUtil() {
    };

    //------------------------------------------------------------------
    // 返回json
    luaSearchUtil.ret_func_json = function (success, msg, data, res){
        var obj = {
            success: success,
            msg: msg,
            data: data
        };
        // 返回
        res.set('Content-Type', 'application/json');
        res.json(obj);
    };

    //------------------------------------------------------------------
    // 测试用
    luaSearchUtil.test = function(func, para, callback){
        luaSearchRedisMgrUtil.getSearchDBMgr(function(error, scriptManager){
            if(!scriptManager){
                return callback(error, null);
            }

            if('lua2_add_design' == func){
                var keys    = [];
                var values  = [1, 1,11,111, '1111,1112',2,'1113,1114','{"id":1,"name":"template"}', 1];

                scriptManager.run(func, keys, values, function(err, result) {
                    var values  = [3, 3,33,333, '3331,3332',1,'3333,3334','{"id":3,"name":"PPT"}', 2];
                    scriptManager.run(func, keys, values, function(err, result) {
                        callback(err, result);
                    });
                });

            }else if('lua2_search_design' == func){
                var keys    = [];
                //var values  = ['1,3', '1111,1112',2,'1114,1115',0,10];// 搜索分类1
                var values  = [para.types, para.labels, para.colors, para.price_type,  para.keywords, para.page_num, para.page_size];// 搜索所有
                scriptManager.run(func, keys, values, function(err, result) {
                    callback(err, result);
                });

            }else if('lua2_del_all' == func){
                var keys    = [];
                var values  = [];
                scriptManager.run(func, keys, values, function(err, result) {
                    callback(err, result);
                });

            }else {
                callback('No func', null);
            }
        })

    };

    //------------------------------------------------------------------
    /* 切换search_db和search_cache_db
     * @param callback,参数如下：
     *              error:
     *              searchDB:
     * */
    luaSearchUtil.switchDB = function(callback){
        luaSearchRedisMgrUtil.switchDB(callback);
    };

    //------------------------------------------------------------------
    /* 获取search_db
     * @param callback,参数如下：
     *              error:
     *              searchDB:
     * */
    luaSearchUtil.getSearchDB = function(callback){
        luaSearchRedisMgrUtil.getSearchDB(callback);
    };
    //------------------------------------------------------------------
    /* 将keywords中的标签提取出来，返回标签id数组
     * @param keywords ：关键字字符串，形如："海报,邀请函"，空字符串表示不限
     * @param callback,参数如下：
     *              error:
     *              newKeywords:    关键字字符串，"海报,邀请函"
     *              newLabels:      标签id字符串，"1,2,3"
     * */
    luaSearchUtil.keywordsToLabelIds = function(keywords, callback){
        var entity = new TgKeywordModel();
        entity.find_name = keywords;
        entity.findKeyByNames(function(error, items){
            if(error || !items){
                return callback(error, null,null);
            }
            var keyarr = entity.find_name.split(",");
            var labelArr = [];

            for(var j=keyarr.length-1;j>=0;j-- ) {
                if (!keyarr[j])  continue;
                var find = false;

                for (var i = 0; i < items.length; i++) {
                    var one = items[i];
                    if (!one.key_name)  continue;

                    if (one.key_name.indexOf(keyarr[j]) >= 0) {
                        labelArr.push(one.key_id);
                        find = true;
                    }
                }

                if(find){
                    keyarr.splice(j, 1);
                }
            }

            return callback(null, keyarr.join(","), labelArr.join(","));
        }, 1);
    }

    //------------------------------------------------------------------
    /* 搜索
     * @param para参数，对象结构，包含以下成员：
     *              types:分类id字符串，不限一二三级，形如："1,2,3"，空字符串表示不限
     *              labels：标签id字符串，不限行业、颜色、自定义等，形如："10,20,30"，空字符串表示不限
     *              colors：颜色id字符串，不限行业、颜色、自定义等，形如："10,20,30"，空字符串表示不限
     *              price_type：费用类型，-1不限 1免费, 2vip，－1表示不限
     *              keywords ：关键字字符串，形如："1,2,3"，空字符串表示不限
     *              page_num：页码
     *              page_size：页数
     * @param callback,参数如下：
     *              error:
     *              data:搜索结果，数组类型：
     *                        第0个元素表示：错误码，0表示没有错误
     *                        第1个元素表示：搜索结果列表的JSON字符串
     *                        第2个元素表示：总页数
     * */
    luaSearchUtil.searchInRedis = function(para, callback){
        luaSearchRedisMgrUtil.getSearchDBMgr(function(error, scriptManager){
            if(!scriptManager){
                return callback(error, null);
            }

            // 将关键字中与标签相同的部分提取成标签id的数组
            luaSearchUtil.keywordsToLabelIds(para.keywords, function(error, newKeywords, newLabels){
                var k = para.keywords;
                var l = para.labels;
                if(newKeywords!=null  && newLabels!=null ){
                    k = newKeywords;
                    l = newLabels;
                }

                var keys    = [];
                //var values  = ['1,3', '1111,1112',2,'1114,1115',0,10];// 搜索分类1
                var values  = [para.types, l, para.colors, para.price_type,  k, para.page_num, para.page_size];// 搜索所有
                scriptManager.run('lua2_search_design', keys, values, function(err, result) {
                    callback(err, result);
                });
            });
        });


    };
    //------------------------------------------------------------------
    /* 搜索
     * @param 清空缓存DB
     * @param callback,参数如下：
     *              error:
     * */
    luaSearchUtil.delAllSearchCache = function(callback){
        luaSearchRedisMgrUtil.getCacheDBMgr(function(error, scriptManager){
            if(!scriptManager){
                return callback(error, null);
            }

            var keys    = [];
            var values  = [];
            scriptManager.run('lua2_del_all', keys, values, function(err, result) {
                callback(err, result);
            });
        });


    };

    //------------------------------------------------------------------
    /**
     * 获取PPT模版的信息
     * @param tmplId PPT模版id
     * @param callback,参数如下：
     *          error：
     *          list:
     *            [
     *              designId
     *              typeL
     *              typeM
     *              typeS
     *              labels
     *              priceType // 费用类型，1免费, 2vip
     *              keywords
     *              info
     *              sort 创建时的时间戳作为排序字段
     *            ]
     */
    luaSearchUtil.getInfoOfPPT = function(tmplId, callback) {
        // 获取分类
        var entity = new ItbTemplateModel({
            tmpl_id:tmplId,
            del_flg:0
        });
        entity.getBaseInfo2(function(error, baseInfo){
            if(error || baseInfo.length==0){
                return callback(error, null);
            }

            entity.getSearchInfo(function(error, searchInfo){
                if(error || searchInfo.length==0){
                    return callback(error, null);
                }

                luaSearchUtil.getKeywords([baseInfo[0].designName, searchInfo[0].type_desc], function(error, keywords) {
                    if (error) {
                        return callback(error, null);
                    }


                    var data = [];
                    for(var i=0;i<baseInfo.length;i++){
                        var one = baseInfo[i];
                        if(one){
                            // 拼接labels和colors
                            var b = one;
                            var labels = '';
                            var colors = '';
                            function local_assemble(source, out){
                                if(source&& source.length>0) {
                                    if(out.length>0){
                                        out +=',';
                                    }
                                    out += source;
                                }
                                return out;
                            }
                            labels = local_assemble(b.industries, labels);
                            labels = local_assemble(b.scenes, labels);
                            labels = local_assemble(b.styles, labels);
                            labels = local_assemble(b.customs, labels);
                            colors = local_assemble(b.colors, colors);


                            data.push({
                                designId:tmplId,
                                typeL:one.typeL ,
                                typeM:one.typeM ,
                                typeS:one.typeS ,
                                labels:labels,
                                colors:colors,
                                priceType:one.vip==10?2:0,
                                keywords:keywords==null?'':keywords,
                                info:JSON.stringify(searchInfo[0]),
                                sort:baseInfo[0].sort
                            });
                        }
                    }

                    return callback(null, data);
                });

            });
        });
    }
    //------------------------------------------------------------------
    /**
     * 获取分词
     * @param text 数组，["蓝色商务名片","褐色古典名片"]
     * @param callback,参数如下
     *          error：
     *          keywords:如果为空则返回空字符串, 分词后关键字，多个之间以半角逗号分割
     */
    luaSearchUtil.getKeywords = function (text, callback){
        var segArr = [];
        for(var i=0;i<text.length;i++){
            var s = tg3Util.doSegmentOfText(text[i],2,20);
            if(s){
                segArr = segArr.concat(s);
            }
        }

        var segKeyword = segArr.join(",");
        return callback(null, segKeyword);
    }
    //------------------------------------------------------------------
    /**
     * 获取分词
     * @param text 数组，["蓝色商务名片","褐色古典名片"]
     * @return  keywords:如果为空则返回空字符串, 分词后关键字，多个之间以半角逗号分割
     */
    luaSearchUtil.getKeywordsSync = function (text){
        var segArr = [];
        for(var i=0;i<text.length;i++){
            var s = tg3Util.doSegmentOfText(text[i],2,20);
            if(s){
                segArr = segArr.concat(s);
            }
        }

        var segKeyword = segArr.join(",");
        return segKeyword;
    }
    //------------------------------------------------------------------
    /**
     * 获取设计的信息
     * @param designId 设计design_id
     * @param callback,参数如下：
     *          error：
     *          data
     *              designId
     *              typeL
     *              typeM
     *              typeS
     *              labels
     *              priceType  // 费用类型，1免费, 2vip
     *              keywords
     *              info
     *              sort 创建时的时间戳作为排序字段
     */
    luaSearchUtil.getInfoOfDesign = function(designId, callback) {
        // 获取分类
        var entity = new TgDesignDocModel({
            design_id:designId,
            del_flg:0
        });
        entity.getBaseInfo2(function(error, baseInfo){
            if(error || baseInfo.length==0){
                return callback(error, null);
            }

            entity.getSearchInfo(function(error, searchInfo){
                if(error || searchInfo.length==0){
                    return callback(error, null);
                }

                luaSearchUtil.getKeywords([baseInfo[0].itemDesc, baseInfo[0].designName, searchInfo[0].type_desc], function(error, keywords){
                    if(error){
                        return callback(error, null);
                    }
                    var s = searchInfo[0];
                    if(s.id==null ||   s.w==null || s.h==null || s.thumb==null  || s.price==null){
                        console.log('**************** error: get design data lose  ! '+designId);
                        return callback(error, null);
                    }

                    // 拼接labels和colors
                    var b = baseInfo[0];
                    var labels = '';
                    var colors = '';
                    function local_assemble(source, out){
                        if(source&& source.length>0) {
                            if(out.length>0){
                                out +=',';
                            }
                            out += source;
                        }
                        return out;
                    }
                    labels = local_assemble(b.industries, labels);
                    labels = local_assemble(b.scenes, labels);
                    labels = local_assemble(b.styles, labels);
                    labels = local_assemble(b.customs, labels);
                    colors = local_assemble(b.colors, colors);

                    //
                    var data = {
                        designId:designId,
                        typeL:b.typeL ,
                        typeM:b.typeM ,
                        typeS:b.typeS ,
                        labels:labels,
                        colors:colors,
                        priceType:b.vip==10?2:0 ,
                        keywords:keywords==null?'':keywords,
                        info:JSON.stringify(s),
                        sort:baseInfo[0].sort
                    };
                    return callback(null, data);
                });

            });
        });
    }

    //------------------------------------------------------------------
    /**
     * 清除缓存DB
     * @param callback
     */
    luaSearchUtil.clearSearchCacheDB = function(callback) {
        luaSearchRedisMgrUtil.getCacheDBMgr(function(error, scriptManager){
            if(!scriptManager){
                return callback(error, null);
            }
            var keys    = [];
            var values  = [];
            scriptManager.run('lua2_del_all', keys, values, function(err, result) {
                return callback(err, result);
            });

        });
    }

    //------------------------------------------------------------------
    /**
     * 添加模版到缓存中
     * @param designId 设计id／PPT模版id
     * @param ppt 1表示PPT(需要特殊处理)
     * @param callback
     */
    luaSearchUtil.addDesignToRedis = function(designId, ppt, callback) {
        luaSearchRedisMgrUtil.getCacheDBMgr(function(error, scriptManager){
            if(!scriptManager){
                return callback(error, null);
            }
            // 添加到redis
            function addToRedis(data,callback2){
                if(!data){
                    console.log('**************** error: get design data failed! '+designId);
                    return callback2(null,null);
                }
                //console.log('&&&&&&&&&&&&&&&& item.design_id: '+ designId);
                //return callback(null, null);



                var keys    = [];
                var values  = [data.designId, data.typeL, data.typeM, data.typeS,  data.labels,  data.colors, data.priceType, data.keywords, data.info, data.sort];
                scriptManager.run('lua2_add_design', keys, values, function(err, result) {
                    return callback2(err, result);
                });
            }
            // 添加多个到redis
            function addToRedisEx(list,callback2){
                var subAsyncFuncs = [];
                for(var n in list) {
                    subAsyncFuncs.push((function(idx, data){
                        return function(subCallback){
                            addToRedis(data, function(error, result){
                                return subCallback(error, result);
                            })
                        }
                    })(n, list[n]));
                }
                // 并行执行
                async.series(subAsyncFuncs, function(error, subResults){
                    if(error){
                        console.log('addToRedisEx async Err: '+error);
                        return callback2(error, null);
                    }

                    return callback2(null, null);
                });
            }

            // 分两种情况处理
            if(ppt==1){// PPT
                luaSearchUtil.getInfoOfPPT(designId, function(error, list){
                    return addToRedisEx(list,callback);
                });
            }else{
                luaSearchUtil.getInfoOfDesign(designId, function(error, data){
                    // 过滤掉不需要搜索的数据
                    if(data&& (data.typeL==2
                        ||data.typeL==5
                        ||data.typeL==9
                        ||data.typeL==1010
                        ||data.typeL==1011)){
                        console.log('******* unsuported design, typeL is:'+data.typeL+' ,and id is:'+designId);
                        return callback(null,null);
                    }
                    return addToRedis(data,callback);
                });
            }

        });



    }

    //------------------------------------------------------------------
    /**
     * 从redis缓存中删除模版
     * @param designId 设计id／PPT模版id
     * @param ppt 1表示PPT(需要特殊处理)
     * @param callback
     */
    luaSearchUtil.delDesignFromRedis = function(designId, ppt, callback) {
        luaSearchRedisMgrUtil.getCacheDBMgr(function(error, scriptManager) {
            if (!scriptManager) {
                return callback(error, null);
            }

            // redis删除一条记录
            function delFromRedis(data,callback2){
                if(!data){
                    console.log('**************** error: get design data failed! '+designId);
                    return callback2(null,null);
                }
                var keys    = [];
                var values  = [data.designId, data.typeL, data.typeM, data.typeS,  data.labels, data.priceType, data.keywords];
                scriptManager.run('lua2_del_design', keys, values, function(err, result) {
                    return callback2(err, result);
                });
            }
            // 从redis删除多个记录
            function delFromRedisEx(list,callback2){
                var subAsyncFuncs = [];
                for(var n in list) {
                    subAsyncFuncs.push((function(idx, data){
                        return function(subCallback){
                            delFromRedis(data, function(error, result){
                                return subCallback(error, result);
                            })
                        }
                    })(n, list[n]));
                }
                // 并行执行
                async.series(subAsyncFuncs, function(error, subResults){
                    if(error){
                        console.log('delFromRedisEx async Err: '+error);
                        return callback2(error, null);
                    }

                    return callback2(null, null);
                });
            }

            // 分两种情况处理
            if(ppt==1){// PPT
                luaSearchUtil.getInfoOfPPT(designId, function(error, list){
                    return delFromRedisEx(list,callback);
                });
            }else{
                luaSearchUtil.getInfoOfDesign(designId, function(error, data){
                    return delFromRedis(data,callback);
                });
            }

        });
    }

    //------------------------------------------------------------------
    /**
     * 查询建立缓存的状态
     * @param callback，回调，返回如下：
            error:
            data:
                {
                     "buildCacheStart":"2017-08-08 10:02:18",   // 建缓存开始时间
                     "buildCacheEnd":"2017-08-08 10:02:18",   // 建缓存结束时间
                     "buildDuration":"500",    // 开始到现在的持续时间,单位秒
                     "buildEstimate”:”600"   //  预估建立缓存时间,单位秒
                }
     */
    luaSearchUtil.querySearchCacheStatus_v1_1 = function(callback) {
        luaSearchRedisMgrUtil.getConfigDBMgr(function(error, scriptManager) {
            if (!scriptManager) {
                return callback(error, null);
            }
            var keys    = [];
            var values  = [];
            scriptManager.run('lua2_query_search_cache_status_v1_1', keys, values, function(err, result) {
                if(err){
                    return callback(err, null);
                }
                var data = {
                    buildEstimate:600
                };
                if(result[1] && result[1].length>0){
                    data.buildCacheStart = result[1];
                }
                if(result[2] && result[2].length>0){
                    data.buildCacheEnd = result[2];
                }

                if(data.buildCacheStart){
                    var end = data.buildCacheEnd?data.buildCacheEnd:CommonUtil.currentTime();
                    data.buildDuration = CommonUtil.timeToTotalSeconds(end)
                                        -CommonUtil.timeToTotalSeconds(data.buildCacheStart);
                }

                return callback(null, data);
            });

        });

    }
    //------------------------------------------------------------------
    /**
     * 设置缓存开始时间
     * @param startTime 开始时间
     * @param callback
     */
    luaSearchUtil.safeSetBuildCacheStart_v1_1 = function(startTime, callback) {
        luaSearchRedisMgrUtil.getConfigDBMgr(function(error, scriptManager) {
            if (!scriptManager) {
                return callback(error);
            }

            // 1、设置 buildCacheStart，并返回

            var keys    = [];
            var values  = [startTime];
            scriptManager.run('lua2_safe_set_build_cache_start_v1_1', keys, values, function(err, result) {
                if (err ) {
                    // 发生异常需要返回
                    return callback(err);
                }

                // 2、直接返回
                if(result!=0){
                    return callback("luaSearchUtil.safeSetBuildCacheStart_v1_1 error : "+result);
                }else{

                    return callback(null);
                }



            });
        });
    }
    //------------------------------------------------------------------
    /**
     * 设置缓存结束时间
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param callback
     */
    luaSearchUtil.safeSetBuildCacheEnd_v1_1 = function(startTime, endTime, callback) {
        luaSearchRedisMgrUtil.getConfigDBMgr(function(error, scriptManager) {
            if (!scriptManager) {
                return callback(error);
            }

            var keys    = [];
            var values  = [startTime, endTime];
            scriptManager.run('lua2_safe_set_build_cache_end_v1_1', keys, values, function(err, result) {
                if (err) {
                    console.log(err);
                    return callback(err);
                }
                // 2、直接返回
                if(result!=0){
                    return callback("luaSearchUtil.safeSetBuildCacheEnd_v1_1 error : "+result);
                }else{
                    return callback(null);
                }
            });
        });
    }
    //------------------------------------------------------------------
    /**
     * 切换搜索DB
     * @param callback
     */
    luaSearchUtil.switchBuildSearchDB_v1_1 = function(callback) {
        luaSearchRedisMgrUtil.getConfigDBMgr(function(error, scriptManager) {
            if (!scriptManager) {
                return callback(error, null);
            }

            var keys    = [];
            var values  = [];
            scriptManager.run('lua2_safe_switch_db_v1_1', keys, values, function(err, result) {
                if (err ) {
                    return callback(err, null);
                }
                if(result!=0){
                    return callback(result==1?"没有创建缓存开始时间或者结束时间，请重试！或者联系二师兄！":result);
                }
                return callback(null);
            });
        });
    }


            //------------------------------------------------------------------
    return luaSearchUtil;
})();

//------------------------------------------------------------------
module.exports = luaSearchUtil;

